//
//  StoreProblemListViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-20.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "StoreProblemListViewController.h"
#import "DDEAddProblemViewController.h"
#import "MTStatusBarOverlay.h"
#import "ErandReportViewController.h"

@interface StoreProblemListViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *problemList;

@end

@implementation StoreProblemListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.problemList = [NSMutableArray array];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshViewByReloadData {
    if ([self.erandInfo count] > 0) {
        NSString *pc = [self.erandInfo objectForKeyOrNil:@"pc"];
        [self getStoreProblemListWithPici:pc];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    self.title = @"临店项目";
    self.showLeftBtn = YES;
    self.showRightBtn = YES;
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_n.png"] forState:UIControlStateNormal];
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_p.png"] forState:UIControlStateHighlighted];
    
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"bar_icon_提交_p.png"] forState:UIControlStateNormal];
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"bar_icon_提交_p.png"] forState:UIControlStateHighlighted];
    
    [self performSelector:@selector(refreshViewByReloadData) withObject:nil afterDelay:0.3];
}

- (void)leftNavItemAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightNavItemAction:(id)sender {
    
    NSString *problemIDList = @"";
    
    BOOL finished = YES;
    
    for (int i = 0; i < [self.problemList count]; i ++) {
        NSDictionary *problemInfo = [self.problemList objectAtIndex:i];
        BOOL submitted = [[problemInfo objectForKey:@"sftj"] boolValue];
        
        if (submitted) {
            NSString *ID = [problemInfo objectForKeyOrNil:@"id"];
            if ([problemIDList length] > 0) {
                problemIDList = [problemIDList stringByAppendingFormat:@",%@",ID];
            } else {
                problemIDList = [problemIDList stringByAppendingFormat:@"%@",ID];
            }
        } else {
            BOOL needed = [[problemInfo objectForKeyOrNil:@"sfbx"] boolValue];
            if (needed) {
                finished = NO;
                break;
            }
        }
    }
    
    if (finished) {
        if ([problemIDList length] > 0) {
            NSString *pc = [self.erandInfo objectForKeyOrNil:@"pc"];
            UserInfo *user = [UserInfo instance];
            NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
            NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                                   problemIDList,@"id",
                                   pc,@"pc",
                                   gonghao,@"gh",
                                   nil];
            [self.networkManager requestWithMethod:allProjectSubmit parameter:param delegate:self];
            [self.HUD show:YES];
        }
    } else {
        NSString *msg = @"有规定必须完成的临店项目没有完成";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

/**
 *  查询某个批次的临店项目列表
 *
 *  @param pc 批次号
 */
- (void)getStoreProblemListWithPici:(NSString *)pc {
    if ([pc length] == 0) {
        return;
    }
    
    if (!self.isRefreshing) {
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               gonghao,@"gh",
                               pc,@"pc",
                               nil];
        if([self sfbg]){
            [self.networkManager requestWithMethod:projects2 parameter:param delegate:self];
        } else {
            [self.networkManager requestWithMethod:projects parameter:param delegate:self];
        }
        [self.HUD show:YES];
        self.isRefreshing = YES;
    }
    
}

- (void)showErandReport {
    ErandReportViewController *reportVC = (ErandReportViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ErandReportView"];
    reportVC.applyInfo = self.erandInfo;
    [self.navigationController pushViewController:reportVC animated:YES];
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    
    if (methodId == projects || methodId == projects2) {
        self.isRefreshing = NO;
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                self.problemList = [NSMutableArray array];
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *problems = [dataObject objectForKeyOrNil:@"projects"];
                        if (![problems isKindOfClass:[NSNull class]] && [problems count] > 0) {
                            [self.problemList  addObjectsFromArray:problems];
                        }
                    }
                }
                
                [self.tableView reloadData];
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    msg = @"临店项目获取失败，请稍后重试";
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
    } else if (methodId == allProjectSubmit) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                BOOL successed = NO;
                NSString *msg = @"";
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSInteger resultCode = [[dataObject objectForKey:@"result"] integerValue];
                        if (resultCode == 2) { //提交成功
                            
                            successed = YES;
                            
//                            MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                            overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                            overlay.detailViewMode = MTDetailViewModeDetailText;
//                            overlay.delegate = nil;
//                            overlay.progress = 0.0;
//                            [overlay postFinishMessage:@"临店项目提交成功！" duration:1.6 animated:YES];
//                            overlay.progress = 1.8;
                            
                            [self showAlertViewWithMessage:@"临店项目提交成功"];
                            
                            [self performSelector:@selector(showErandReport) withObject:nil afterDelay:0.9];
                        } else if (resultCode == 0) {
                            msg = @"系统异常，临店项目提交失败";
                        } else if (resultCode == 1) {
                            msg = @"有规定必须完成的临店项目没有完成";
                        }
                    }
                }
                
                if (!successed) {
                    if ([msg length] == 0) {
                        msg = @"临店项目提交失败，请稍后重试";
                    }
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:msg
                                                                   delegate:nil
                                                          cancelButtonTitle:@"确定"
                                                          otherButtonTitles:nil];
                    [alert show];
                }
                
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    msg = @"临店项目提交失败，请稍后重试";
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            if (methodId == projects || methodId == projects2) {
                msg = @"临店项目获取失败，请稍后重试";
            } else if (methodId == allProjectSubmit) {
                msg = @"临店项目提交失败，请稍后重试";
            }
        }
    }
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (void)updateRightItemButtonWithSelectFlag:(BOOL)selected {
    if (selected) {
        [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"bar_icon_提交_p.png"] forState:UIControlStateNormal];
        [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"bar_icon_提交_p.png"] forState:UIControlStateHighlighted];
    } else {
        [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"bar_icon_提交_n.png"] forState:UIControlStateNormal];
        [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"bar_icon_提交_n.png"] forState:UIControlStateHighlighted];
    }
    self.rightBtn.enabled = selected;
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //    return 5;
    return [self.problemList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"StoreProblemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    
    UILabel *label1 = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *label2 = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *label3 = (UILabel *)[cell.contentView viewWithTag:103];
    UILabel *label4 = (UILabel *)[cell.contentView viewWithTag:104];
    
    NSInteger row = indexPath.row;
    
    if ([self.problemList count] > row) {
        NSDictionary *cellData = [self.problemList objectAtIndex:row];
//        NSInteger ldpc = [[cellData objectForKeyOrNil:@"ldpc"] integerValue]; //临店批次
        NSString *name = [cellData objectForKeyOrNil:@"xmmc"]; //项目名称
        BOOL needPhoto = [[cellData objectForKeyOrNil:@"sfpz"] boolValue]; //是否需要拍照
        BOOL mustFinish = [[cellData objectForKeyOrNil:@"sfbx"] boolValue]; //是否必须完成
        BOOL submitted = [[cellData objectForKeyOrNil:@"sftj"] boolValue]; //是否已提交
        
        NSString *strTitle = @"";
        if (mustFinish) {
            strTitle = @"必须完成";
        }
        label1.text = strTitle;
        label3.text = name;
        
        NSString *needName = @"";
        if (needPhoto) {
            needName = @"需拍照";
        } else {
            needName = @"";
        }
        
//        if (mustFinish) {
//            if ([needName length] > 0) {
//                needName = [needName stringByAppendingFormat:@",必须完成"];
//            } else {
//                needName = @"必须完成";
//            }
//        }
        
        label2.text = needName;
        
        if (submitted) {
            label4.text = @"已提交";
        } else {
            label4.text = @"";
        }
        
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60.0;
}
NSDictionary *data = nil;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIAlertView *alert = nil;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    
    
    BOOL canSelected = NO;
    
    if ([self.problemList count] > row) {
        data = [self.problemList objectAtIndex:row];
        
        BOOL submitted = [[data objectForKeyOrNil:@"sftj"] boolValue];
        
        if (submitted) {
            alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"该项目已完成"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles: nil];
            [alert show];
            
            canSelected = NO;
        } else {
            if (row == 0) {
                canSelected = YES;
            } else {
                BOOL preSubmitted = NO;
                
                NSInteger preRow = row - 1;
                NSDictionary *preData = [self.problemList objectAtIndex:preRow];
                preSubmitted = [[preData objectForKeyOrNil:@"sftj"] boolValue];
                
                if (preSubmitted) {
                    canSelected = YES;
                } else {
                    canSelected = NO;
                    
                    alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:@"请完成上面的项目再进行该项的操作"
                                                                   delegate:nil
                                                          cancelButtonTitle:@"确定"
                                                          otherButtonTitles: nil];
                    [alert show];
                }
                
            }
        }
    }
    
    if (canSelected) {
        
        alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@""
                                                       delegate:self
                                              cancelButtonTitle:@"新增问题"
                                              otherButtonTitles:@"查看详情",nil];
        alert.tag = 1000;
        [alert show];
        
    }
    
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1000) {
        if (buttonIndex == alertView.cancelButtonIndex) {
                DDEAddProblemViewController *addProblemVC = (DDEAddProblemViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"DudaoAddProblemView"];
                    addProblemVC.problemInfo = data;
                    addProblemVC.erandInfo = self.erandInfo;
                    [self.navigationController pushViewController:addProblemVC animated:YES];
        } else if (buttonIndex == alertView.firstOtherButtonIndex) {
            NSString *name = [data objectForKeyOrNil:@"xmms"];
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"项目详情" message:name delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            
            [alter show];
        }
    }
}


@end
